package net.acnull.arpg.rpg.skill.skills;

import com.destroystokyo.paper.ParticleBuilder;
import net.acnull.arpg.cooldown.CooldownManager;
import net.acnull.arpg.effect.Light;
import net.acnull.arpg.rpg.skill.Skill;
import org.bukkit.*;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;

import java.util.Map;
import java.util.UUID;

public class SprintSkill implements Skill{

    private final int range;
    private final ParticleBuilder builder;
    private final int cooldown;
    private final int damage;

    public SprintSkill(int range, ParticleBuilder builder,int cooldown,int damage){
        this.range=range;
        this.builder=builder;
        this.cooldown=cooldown;
        this.damage=damage;
    }


    @Override
    public void onClick(Player player, Action action) {
        if(action!=Action.RIGHT_CLICK_AIR&&action!=Action.RIGHT_CLICK_BLOCK){
            return;
        }
        Map<UUID,Integer> map= CooldownManager.getInstance().getMap("sprint");
        if(map.containsKey(player.getUniqueId())){
            return;
        }
        Location loc=player.getLocation();
        double deltaX=Math.cos(Math.toRadians(loc.getYaw()+90));
        double deltaZ=Math.sin(Math.toRadians(loc.getYaw()+90));
        for(int i=0;i<range;i++){
            loc.add(deltaX,0,deltaZ);
            if(loc.getBlock().getType().isSolid()){
                loc.subtract(deltaX,0,deltaZ);
                break;
            }
           loc.getWorld()
                    .getNearbyEntities(loc, 0.5, 0.2, 0.5).stream()
                    .filter(entity -> entity != player && entity instanceof LivingEntity)
                    .forEach(e->{
                        EntityDamageByEntityEvent event=new EntityDamageByEntityEvent(player,e, EntityDamageEvent.DamageCause.CUSTOM,damage);
                        Bukkit.getPluginManager().callEvent(event);
                        if(event.isCancelled()){
                            return;
                        }
                        ((LivingEntity) e).setHealth
                                (Math.max(((LivingEntity) e).getHealth()- event.getFinalDamage(),0));
                        e.playEffect(EntityEffect.HURT);
                    });
            builder.location(loc).spawn();
            new Light(loc.clone(),2,15).create();
        }
        player.teleport(loc);
        map.put(player.getUniqueId(),cooldown);
    }

    @Override
    public void onDamage(LivingEntity entity) {

    }
}
